//获取当前时间
var d = new Date();
var m = d.getMonth() + 1;
var currentTime = d.getFullYear() + "-" + m + "-" + d.getDate() + " "
		+ d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();// 当前日期
var currentDate = d.getFullYear() + "-" + m + "-" + d.getDate();
// 当年1月1日
var startTime = new Date(Date.parse((d.getFullYear() + "-01-01").replace(/-/g,
		"/")));

//熄弧时间概率分布
var arcProperty;
var gd1;

// 断路器动作时间概率分布
var actProperty;
var actData ;// 动作时间array
var scrollHeight=500;
$(function() {
	var iMainH = parseInt($("#main_content").css("min-height")) - 20;
	scrollHeight=iMainH-300;
	$("#arcProperty").css("height",scrollHeight);
	var t1 = window.setInterval(function() {
		var w = $('#pane2').width() + "";
		if (w != '0') {
			$("#arcProperty").css("width", w/2  - 20);
			$("#arcPie").css("width", w/2  - 20);
			//$("#actProperty").css("width", w / 2 - 20);
			$("#actPie").css("width", w  - 20);
			getXiHuTime();
			getActData();
			getScatterData();
			window.clearInterval(t1);
		}
	}, 20);
	$('#startTime1').datetimepicker({
		minView : 2,
		autoclose : true,
		format : 'yyyy-mm-dd'
	});
	$('#endTime1').datetimepicker({
		minView : 2,
		autoclose : true,
		format : 'yyyy-mm-dd'
	});
	$('#startTime2').datetimepicker({
		minView : 2,
		autoclose : true,
		format : 'yyyy-mm-dd'
	});
	$('#endTime2').datetimepicker({
		minView : 2,
		autoclose : true,
		format : 'yyyy-mm-dd'
	});
	$('#check-btn1').click(function() {
		getXiHuTime();
	});
	$('#check-btn2').click(function() {
		getActData();
	});
	$('#tab1').click(function(){
		var t1 = window.setInterval(function() {
			var w = $('#pane1').width() + "";
			if (w != '0') {
				$("#abnormalArcTimeTbWrap").css("width", w  - 20);
				if(tb){
					tb.getTable().draw();
				}
				window.clearInterval(t1);
			}
		}, 20);
		
	});
});

function getArcOption() {
	var option = {
		vol : '',
		type : '',
		manufacturer : '',
		model : '',
		startDate:"",
		endDate:""
	};
	option.vol = $("#voltage1").val();
	option.type = $("#type1").val();
	option.startDate = $("#startTime1").val();
	option.endDate = $("#endTime1").val();
	option.manufacturer = $("#manufacture1").val();
	option.model = $("#model1").val();

	return option;
}
function getActOption() {
	var option = {
		vol : '',
		type : '',
		manufacturer : '',
		model : '',
		startDate:"",
		endDate:""
	};
	option.vol = $("#voltage2").val();
	option.type = $("#type2").val();
	option.startDate = $("#startTime2").val();
	option.endDate = $("#endTime2").val();
	option.manufacturer = $("#manufacture2").val();
	option.model = $("#model2").val();

	return option;
}
// 初始化加载熄弧时间概率分布
function getXiHuTime() {
	var option = getArcOption();
	$.getJSON("/rest/breakerRunSafe/getBreakerActInfosForArc/"+JSON.stringify(option), function(result) {
		var arcTimeList = [];
		var arcData=[];
		for ( var i in result) {
			arcData.push(result[i].xhTimeInterval/1000);
			arcTimeList.push([ result[i].stationId, result[i].breakerId,
					result[i].stationName, result[i].lineName,
					result[i].breakerName, result[i].faultTime,
					result[i].phase, result[i].xhTimeInterval/1000,result[i].faultFileId,
					result[i].twTime,result[i].analogFirstActionTime,result[i].cross0Time,result[i].actionTimeInterval ]);
		}
		//
		initArcPieData(arcData);
		//arcProperty=initDensityChart(arcData,'arcProperty','arc');
		initArcChart(arcData);
		abnormalArc(arcTimeList);
		$("#totalNum").html(result.length);
	});
}
function initArcChart(timeArray){
	var skewDistribution = new SkewDistribution(timeArray);
	skewDistribution.init();
	var xData=skewDistribution.getXData();
	var yData=skewDistribution.getYData();
	var lineYData=yData.slice(0);
	//lineYData.splice(1,1);
	var option = {
		    xAxis: [{
		        type: 'category',
		        data:xData,
		        name:"熄弧时间(ms)"
		    }],
		    yAxis: {
		        splitLine: {
		            lineStyle: {
		                color: 'rgba(131,101,101,0.2)',
		                type: 'dashed',
		            }
		        },
		        name:'次数'
		    },
		    tooltip: {
		        trigger: 'axis',
		        axisPointer: {
		            type: 'cross'
		        }
		    },
		    dataZoom: [{
		        type: 'inside'
		    }, {
		        type: 'slider'
		    }],
		    series: [{
		        type: 'bar',
		        data: yData,
		        name: '平均频次',
		       
		    }, {
		        data: lineYData,
		        type: 'line',
		        smooth: true,
		        name: '平均频率',
		        showSymbol:false

		    }]
		};
	arcProperty = echarts.init(document.getElementById("arcProperty"));
	arcProperty.setOption(option);
}

function initDensityChart(dataSet,chartId,type) {
	var actProperty = new Category2YLine(chartId);
	// 概率分布
	var gd2 = new GaussianDistribution(dataSet);
	if(type=='arc'){
		gd1 = gd2;
	}
	var obj = gd2.getXData();
	// 动作时间
	var act_avg_time = obj.xData;
	var frequency = obj.xNum;
	var yData = gd2.proDensity(act_avg_time);
	actProperty.setxAxis(act_avg_time);
	actProperty.sety1Axis(frequency);
	actProperty.setyAxisName('频率');
	for ( var i in yData) {
		yData[i] = yData[i].toFixed(2);
	}
	actProperty.sety2Axis(yData);
	actProperty.setyAxisName('概率密度');
	var opt = actProperty.getOption();
	opt.series[0].type = 'bar';
	opt.series[1].smooth = true;
	opt.series[1].areaStyle.normal.opacity = 0;
	opt.series[1].showSymbol = false;
	actProperty.show();
	return actProperty;
}

//动作时间概率分布
function initArcPieData(arcData) {
	arcData.sort(function(a,b){
		return a-b;
	});
	var arcPieData = [];
	var lagTimeMap = new Map();
	var max = arcData[arcData.length-1];
	var min = 0;
	var maxValue=0;//所有数值中的最大值
	var gt80Num=0;//大于80的个数
	/*for (var j = min; j <= max; j+=5) {
		var legend = "[" + j + "ms," + (j + 5)  + "ms]";
		arcPieData.push([ legend, 0 ]);
	}*/
	var index=0;
	while(index<=max){
		var legend = "[" +index + "ms," + (index+ 5)  + "ms]";
		arcPieData.push([ legend, 0 ]);
		index+=5;
	}
	
	for(var i in arcData){
		var t = Number(arcData[i]);
		var index=Math.floor(t/5);
		if(t>maxValue){
			maxValue=t;
		}
		if(t>max){
			gt80Num++;
		}else{
			arcPieData[index][1]++;
		}
	}
	if(gt80Num>0){
		var legend = "["+max+"ms," + maxValue + "ms]";
		arcPieData.push([legend,gt80Num]);
	}
	initArcPie(arcPieData);
}
function initArcPie(arcPieData) {
	var arcPie = new Pie("arcPie");
	arcPie.setPie(arcPieData).setPieCenter('50%', '55%').setPieOuterRadius(
			"50%").setPieLabelFormatter("{d}%");
	var opt = arcPie.getOption();
	opt.legend.top = 30;
	arcPie.show();
}

var tb ;
function abnormalArc(arc) {
	if (tb) {
		tb.getTable().destroy();
	}
	//var abnormalArc = gd1.abnormalAnalyse(arc);
	var arcOpt = MyTable.getDefaultOptions();
	arcOpt.scrollY = scrollHeight;
	arcOpt.autoWidth = false;
	arcOpt.scrollX = false;
	arcOpt.columnDefs = [ {
		"targets" : [ 0,1,8,9,10,11,12],
		"visible" : false,
		
	},{
		targets : 2,
		width : '15%'
	}, {
		targets : 3,
		width : '20%'
	}, {
		targets : 4,
		width : '10%'
	}, {
		targets : 5,
		width : '30%'
	}, {
		targets :6,
		width : '10%'
	}, {
		targets : 7,
		width : '15%'
	} ];
	tb = new MyTable('abnormalArcTime', [ '厂站id', '断路器id', '厂站', '线路', '断路器',
			'故障时间', '相别', '熄弧时间(ms)','fileId','actTime','removeTime','cross0Time','actionTimeInterval'], arcOpt);
	var abnormalArc=[];
	for(var i in arc){
		if(arc[i][7]>12){
			abnormalArc.push(arc[i]);
		}
	}
//	abnormalArc.sort(function(a,b){
//		return Date.parse(a[5])-Date.parse(b[5]);
//	});
	
	tb.setDataSet(abnormalArc);
	tb.show();
	tb.onRowClick(function(params) {
		// 弹出一个模态框,展示该站下的该断路器该段时间内的历史熄弧时间
		/*var startTime=$("#startTime1").val()==""?0:$("#startTime1").val();
		var endTime=$("#endTime1").val()==""?0:$("#endTime1").val();
		var stationId=params[0]==""?0:params[0];
		var breakerId=params[1]==""?0:params[1];
		
		$.getJSON("/rest/breakerRunSafe/getArcTimesByBreaker/" + stationId
				+ "/" + breakerId+"/"+startTime+"/"+endTime, function(result) {
			var breakerHisData = [];
			for ( var i in result) {
				breakerHisData.push([ result[i].stationName,
						result[i].breakerName, result[i].faultTime,
						result[i].xhTimeInterval / 1000 ]);
			}
			createPop(breakerHisData);
		});*/
		//弹出熄弧时间分析页面
		$.getJSON('/rest/waveData/getMinProtectActTime/' + params[8] + "/"
				+ params[6], function(result) {
			var url = "/ui/wave/breakerWave.xhtml?fileId="
				+ params[8] + "&breakerId="
				+ params[1] + "&phase="
				+ params[6] + "&actTime="
				+ params[9] + "&removeTime="
				+ params[10]+ "&xhTime="
				+ params[7]*1000+ "&protectAct="
				+ result;
		   var name = params[3]
				+ params[4] + "跳"
				+ params[6] + "("
				+ params[5] + ")";
		   MyModal.showModal(url, null, null, name);
		})
		
	});
	$("#abnormalNum").html(abnormalArc.length);
}
function createPop(data) {
	$("#popTitle").html(data[0][0] + " " + data[0][1] + "断路器 ");
	var xData = [];
	var yData = [];
	for ( var i in data) {
		xData.push(data[i][2]);
		yData.push(data[i][3]);
	}
	var popChart = new CategoryLine("popChart");
	popChart.setTitle("历史熄弧时间").setxAxis(xData).setxAxisTitle("故障时间").setyAxis(
			yData).setyAxisTitle("ms").setyAxisName("熄弧时间");
	var opt = popChart.getOption();
	opt.xAxis.axisLabel.formatter = function(params) {
		var label = params;
		var str1 = label.substr(0, 10);
		var str2 = label.substr(11, label.length);
		return str1 + "\n" + str2;
	};
	popChart.show();
	$("#pop").modal();
	popChart.getChart().resize();
}
// 动作时间概率分布
function initActPieData() {
	var actPieData = [];
	var lagTimeMap = new Map();
	var max = 80;
	var limitValue = 200; //设置正常值的上限
	var min = 0;
	var maxValue=0;//所有数值中的最大值
	var gt80Num=0;//大于80的个数
	for (var j = min; j < max; j+=10) {
		var legend = "[" + j + "ms," + (j + 10)  + "ms]";
		actPieData.push([ legend, 0 ]);
	}
	for(var i in actData){
		var t = Number(actData[i]);
		var index=Math.floor(t/10);
		if(t > limitValue ){
			continue;
		}
		if(t>maxValue){
			maxValue=t;
		}
		
		if(t >= max){
			gt80Num++;
		}else{
			actPieData[index][1]++;
		}
	}
	if(gt80Num>0){
		var legend = "["+max+"ms," + maxValue + "ms]";
		actPieData.push([legend,gt80Num]);
	}
	initActPie(actPieData);
}
var actPie;
function initActPie(actPieData) {
	actPie = new Pie("actPie");
	actPie.setPie(actPieData).setPieCenter('50%', '55%').setPieOuterRadius(
			"50%").setPieLabelFormatter("{d}%");
	var opt = actPie.getOption();
	opt.legend.top = 30;
	actPie.show();
	actPie.getChart().on("click",function(params) {
		var range = params.data["name"].split(',');
		var minRange = range[0].substring(1, range[0].length - 2);
		var maxRange = range[1].substring(0, range[1].length - 3);
		onChartClick(minRange,maxRange);
	});
}
function getActData() {
	var option = getActOption();
	actData=[];
	$.getJSON('/rest/breakerRunSafe/getBreakerActInfos/' + JSON.stringify(option), function(result) {
		for(var i in result){
			actData.push(result[i].distance0MomentsTime / 1000);
		}
		initActPieData();
	});
}

function onChartClick(minRange,maxRange) {
	var option = getActOption();
	$.getJSON('/rest/breakerRunSafe/getBreakerActDetailInfos/' + JSON.stringify(option) + "/" + minRange + "/" + maxRange, function(result) {
		loadDetailTable(result);
	});
	PF('detailDialog').show();
}
var timeColumns = [ "序号", "变电站", "线路", "断路器", "故障时间", "故障类型", "相别", "断路器动作时间间隔",
	"本次动作距离故障0时刻的时间","动作类型","能量积分","熄弧时间间隔","过0点时间","故障0时刻短路电流","开关量第一次动作时间"/*"故障文件id"*/ ];
var table;
function loadDetailTable(detailDatas) {
	if (table) {
		table.getTable().destroy();
	}
	var opt = MyTable.getDefaultOptions();
	opt.paging = false;
	opt.autoWidth = false;
	var defs = [ {
		"width" : "5%",
		"targets" : 0
	},{
		"width" : "8%",
		"targets" : 1
	}, {
		"width" : "10%",
		"targets" : 2
	}, {
		"width" : "5%",
		"targets" : 3
	}, {
		"width" : "8%",
		"targets" : 4
	}, {
		"width" : "5%",
		"targets" : 5
	}, {
		"width" : "5%",
		"targets" : 6
	}, {
		"width" : "7%",
		"targets" : 7
	}, {
		"width" : "10%",
		"targets" : 8
	}, {
		"width" : "5%",
		"targets" : 9
	}, {
		"width" : "5%",
		"targets" : 10
	}, {
		"width" : "8%",
		"targets" : 11
	}, {
		"width" : "8%",
		"targets" : 12
	}, {
		"width" : "8%",
		"targets" : 13
	}, {
		"width" : "8%",
		"targets" : 14
	} ];
	opt.scrollY = 600 + "px";
	opt.scrollX = false;
	var datas = [];
	for ( var i in detailDatas) {
		var f = detailDatas[i];
		datas.push([ Number(i) + 1,f.stationName, f.lineName,f.breakerName,
			f.faultTime, f.faultType, f.phase, f.actionTimeInterval, 
			f.distance0MomentsTime, f.actionType,f.i2t,f.xhTimeInterval,
			f.cross0Time,f.faultValue0,f.statusFirstActionTime/*str(f.faultFileId)*/]);
	}
	var targets = [];
	// 筛选列
	var eles = document.getElementsByName('columns');
	var targets = [];
	for (var i = 0; i < eles.length; i++) {
		if (!eles[i].checked) {
			targets.push(i);
		}
	}
	defs.push({
		visible : false,
		targets : targets
	});
	opt.columnDefs = defs;
	table = new MyTable("detailTable", timeColumns, opt);
	table.setDataSet(datas).show();
}
